from django.utils.deprecation import MiddlewareMixin
from rest_framework.response import Response
from utils.ten_token import verify_jwt
from functools import wraps


class SimMiddleware(MiddlewareMixin):
    def process_request(self, request):
        auth = request.headers.get('Authorization')
        if auth and auth.startswith('JWT '):
            "提取token 0-6 被Bearer和空格占用 取下标7以后的所有字符"
            token = auth[4:]
            "校验token"
            payload = verify_jwt(token)
            "判断token的校验结果"
            if payload:
                request.session.id = payload.get('user_id')
            else:
                request.session.id = None

        else:
            request.session.id = None


def login_required_my(f):
    @wraps(f)
    def wrapper(request, *args, **kwargs):
        if not request.session.id:
            return Response({'message': 'token过期'}, status=401)
        else:
            return f(request, *args, **kwargs)

    # 第2种方法,在返回内部函数之前,先修改wrapper的name属性
    # wrapper.__name__ = f.__name__
    return wrapper